package Listener;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;

public class ListenerServiceImpl implements ListenerService {

	
	private AcceptThread _acptThread = null ;
	class AcceptThread extends Thread {
		//ThreadGroup tg;
		
		Hashtable session = new Hashtable();
		boolean quit = false;
		
		AcceptThread(){
			super( new ThreadGroup("Test Listener"), "Test Socket Listener");
		}
		public void run() {
			//tg = getThreadGroup();
			ServerSocket socket = null;
			
			try {
				socket = new ServerSocket( 1979, 500 );
				//socket.setSoTimeout( 500 );
				
				
				while( !quit )
				{
					//System.out.println("While Start !");
					final Socket client = socket.accept();
					
					
					if(quit){
						client.close();
						break;
					}
				
					Thread startSessionThread = new Thread() 
					{
						private String ReadBuffer( DataInputStream buffer)
						{
							String tmpStr	=	null;
							try {
								tmpStr	=	buffer.readLine();
							
							} catch( IOException e)
							{
								return null;
							}
							return tmpStr;
						}
						public void run() {
							//System.out.println("Session Thread Start !");
							PrintWriter out = null ;
							try{
								out = new PrintWriter( client.getOutputStream(), true );
								InputStream is = client.getInputStream();
								BufferedInputStream buffInput = new BufferedInputStream(is);
								DataInputStream dataInput = new DataInputStream(buffInput);
								//InputStreamReader isr = new InputStreamReader(is);
								//BufferedReader in = new BufferedReader(isr);
								//System.out.println("Thread Run Function !");
								ReadBuffer( dataInput );
							
							} catch( IOException e ) {
								return ;
							}
						}
					};
					startSessionThread.start();
				}
			} catch( Exception e){
				if(quit){
					System.out.println("Listener End.");
					return ;
				}
			}
			
			if( socket != null ) {
				try{
					socket.close();
				} catch(IOException ignore){}
			}
		}
	}
	public void run() {
		_acptThread = new AcceptThread();
		_acptThread.setDaemon(true);
		
		_acptThread.start();
	}

}
